package com.s59.rbac.controller;

import com.s59.rbac.common.R;
import com.s59.rbac.common.Token;
import com.s59.rbac.entity.vo.LoginVO;
import com.s59.rbac.service.ILoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;

@RestController
public class LoginController {
    @Autowired
    private ILoginService loginService;

//    @PostMapping("/login")
//    public R login(@RequestBody LoginVO loginVO){
//        try {
//            Token token = loginService.login(loginVO);
//            return R.ok(token);
//        } catch (LoginException e) {
//            return R.err(e.getMessage());
//        }
//    }
    @PostMapping("/login")
    public R login(@RequestBody LoginVO loginVO){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginVO.getUserName(), loginVO.getPassword());
        try{
            SecurityUtils.getSubject().login(usernamePasswordToken);
        }catch (Exception e){
            return R.err(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/logout")
    public R logout(@RequestHeader String token){
        loginService.logout(token);
        return R.ok();
    }
}
